package com.example.view;

import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.deletelistviewitemdemo.R;
import com.example.view.SlideView.OnSlideListener;

public class SlideAdapter extends BaseAdapter implements OnSlideListener {

	private List<MessageItem> mMessageItems;
	private Context mContext;
	private SlideView mLastSlideViewWithStatusOn;

	/**
	 * @param context
	 * @param messageItems显示的内容
	 */
	public SlideAdapter(Context context, List<MessageItem> messageItems) {
		super();
		this.mContext = context;
		this.mMessageItems = messageItems;
	}

	@Override
	public int getCount() {
		return mMessageItems.size();
	}

	@Override
	public Object getItem(int position) {
		return mMessageItems.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		SlideView slideView = (SlideView) convertView;
		if (slideView == null) {
			View itemView = View.inflate(mContext,
					R.layout.item_listview_delete, null);
			// 将item显示的内容设置到Item对象中
			slideView = new SlideView(mContext);
			slideView.setContentView(itemView);

			holder = new ViewHolder(slideView);
			slideView.setOnSlideListener(SlideAdapter.this);
			slideView.setTag(holder);
		} else {
			holder = (ViewHolder) slideView.getTag();
		}
		MessageItem item = mMessageItems.get(position);
		item.setSlideView(slideView);
		item.getSlideView().shrink();
		holder.tv_content.setText(item.getTv_content());
		holder.deleteHolder.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (deleteItemListener != null) {
					deleteItemListener.deleteItem(v, position);
				}
			}
		});

		return slideView;
	}

	class ViewHolder {
		public TextView tv_content;
		public ViewGroup deleteHolder;

		ViewHolder(View view) {
			tv_content = (TextView) view.findViewById(R.id.tv_content);
			deleteHolder = (ViewGroup) view.findViewById(R.id.holder);
		}
	}

	@Override
	public void onSlide(View view, int status) {

		if (mLastSlideViewWithStatusOn != null
				&& mLastSlideViewWithStatusOn != view) {//不为空，并且点击的不是当前的View。
			mLastSlideViewWithStatusOn.shrink();// 回到圆点
		}

		if (status == SLIDE_STATUS_ON) {
			mLastSlideViewWithStatusOn = (SlideView) view;
		}

	}

	public interface DeleteItemListener {
		public void deleteItem(View view, int position);
	}

	private DeleteItemListener deleteItemListener;

	/**
	 * @param deleteItemListener
	 *            设置删除Item监听事件
	 */
	public void setDeleteItemListener(DeleteItemListener deleteItemListener) {
		this.deleteItemListener = deleteItemListener;
	}

}
